#!/usr/bin/python
# -*- coding:UTF-8 -*-

from enum import Enum
from pathlib import Path
import subprocess
import shutil
import json
import os

Apps = []

# class APP(Enum):
#     APP_VSCODE = 'visual-studio-code'
#     APP_BREW = 'brew'
#     APP_MAS = 'mas'


# def backup(app: Enum):
#     if app == APP.APP_VSCODE:
#         print(app.value)
#     else:
#         print('else')


#备份文件夹
def backup_path():
    backup_path = Path(__file__).parent/'backup'
    createFileIfNeeded(backup_path)
    return backup_path


#json 存本地
def saveLocal(Apps):
    with open(backup_path()/'apps.json','w',encoding='utf-8') as json_file:
        json.dump(Apps,json_file,ensure_ascii=False)

#需要时创建文件夹
def createFileIfNeeded(path):
    #不存在创建
    if not Path(path).exists():
        Path(path).mkdir(parents=True,exist_ok=True)

#check cmd if exsits
def exsits(cmd):
    exsits_cmd = 'which ' + cmd
    exsits = os.system(exsits_cmd) == 0
    print('%s %s exsits!' %(cmd,exsits))
    return exsits

#
def getApps(list_cmd):
    applist_ifno = os.popen(list_cmd).readlines()
    applist = []
    for app in applist_ifno:
        app = app.replace('\n', '')
        if len(app) > 0:
            applist.append(app.replace('\n', ''))
    return applist


# backup /Applications
def backup_Applications():
    application_apps_cmd = 'ls -l /Applications | awk \'{$1=$2=$3=$4=$5=$6=$7=$8=""; print}\' | sed -E \'s/^ +//g\' | sed \'s/\.app//g\''
    Apps.append({"application":getApps(application_apps_cmd)})

#     1 model={} #存放读取的数据
# 2 with open("./hmm.json",'r',encoding='utf-8') as json_file:
# 3         model=json.load(json_file)

#backup AppStore
def backup_mas():
    if exsits('mas'):
        appstore_apps_cmd = 'mas list'
        Apps.append({"mas":getApps(appstore_apps_cmd)})

#backup brew
def backup_brew():
    if exsits('brew'):
        brew_apps_cmd = 'brew list'
        Apps.append({"brew":getApps(brew_apps_cmd)})
        brew_cask_cmd = 'brew cask list'
        Apps.append({"brew cask":getApps(brew_cask_cmd)})


#backup zsh
def backup_oh_my_zsh():
    zshrc_path = Path().home()/'.zshrc'
    shutil.copyfile(zshrc_path,backup_path()/'zshrc')


#backup vscode extensions
def backup_vscode_extensions():
    if exsits('code'):
        vscode_extensions_cmd = 'code --list-extensions'
        Apps.append({"code":getApps(vscode_extensions_cmd)})

backup_mas()
backup_brew()
backup_Applications()
backup_vscode_extensions()
backup_oh_my_zsh()

saveLocal(Apps)


os.system('say \'备份成功\'')



# default_commands = ['ls -l /Applications | awk \'{$1=$2=$3=$4=$5=$6=$7=$8=""; print}\' | sed -E \'s/^ +//g\' | sed \'s/\.app//g\'']
# custom_commands = ['brew','code','mas','zsh']

# subprocess.open([])
